<template>
  <div class="container-fluid mt-3">
    <!-- 面包屑导航 -->
    <div class="mt-5 border border-2 overflow-x-auto">
      <span
        v-for="(item, index) in path"
        :key="index"
        class="bg-body-secondary btn me-1"
        @click="navigateToFolder(item)"
      >
        {{ item.name }}/
      </span>
    </div>

    <!-- 操作按钮组 -->
    <div class="d-flex mt-5">
      <el-button size="small" @click="showCreateDialog">新建文件夹</el-button>
      <el-upload
        ref="upload"
        :action="uploadApi"
        :on-error="handleUploadError"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
      >
        <el-button size="small" type="primary">选择文件</el-button>
      </el-upload>
      <el-button size="small">清空</el-button>
    </div>

    <!-- 文件列表 -->
    <div class="row bg-white">
      <div
        v-for="item in fileList"
        :key="item.id"
        class="bg-light m-3 file-item"
        @click="navigateToFolder(item)"
      >
        <img
          :src="item.is_file ? require('@/assets/文件.svg') : require('@/assets/文件夹.svg')"
          alt=""
          class="file-icon"
        >
        <div class="text-center">{{ item.name }}</div>
        <div>
          <el-button size="small" @click.stop="showEditDialog(item)">编辑</el-button>
          <el-button size="small" @click.stop="deleteItem(item)">删除</el-button>
          <el-button
            size="small"
            @click.stop="downloadFile(item)"
            v-if="item.is_file"
          >
            下载
          </el-button>
        </div>
      </div>
    </div>

    <!-- 编辑/创建对话框 -->
    <el-dialog
      :title="isEditMode ? '编辑' : '新建'"
      :visible.sync="showDialog"
      @close="resetForm"
    >
      <el-form>
        <el-form-item label="名称">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="formData.public"></el-switch>
        </el-form-item>
        <el-form-item label="类型" v-if="!isEditMode">
          <el-radio-group v-model="formData.is_file">
            <el-radio :label="true">文件</el-radio>
            <el-radio :label="false">文件夹</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {FileApi, user_space_create, user_space_delete, user_space_get_content, user_space_update} from "@/api/api";
import {getJson, postJson} from "@/api/http";

export default {
  name: "UserSpace",
  data() {
    return {
      uploadApi: process.env.VUE_APP_BASE_URL + FileApi,
      path: [{ name: "根目录" }],  // 更友好的默认名称
      fileList: [],
      formData: this.getDefaultFormData(),
      showDialog: false,
      isEditMode: false
    };
  },
  computed: {
    currentFolderId() {
      return this.path.length > 0
        ? this.path[this.path.length - 1].id
        : null;
    }
  },
  mounted() {
    this.loadFolderContent();
  },
  methods: {
    getDefaultFormData() {
      return {
        name: '',
        public: false,
        is_file: false,
        path: '',
        parent_id: null
      };
    },

    resetForm() {
      this.formData = this.getDefaultFormData();
      this.isEditMode = false;
    },

    async loadFolderContent(folderId = null) {
      try {
        const params = folderId ? { parent_id: folderId } : {};
        const res = await getJson(user_space_get_content, params);

        if (res.code !== 1) {
          throw new Error(res.msg || '操作失败');
        }

        this.fileList = res.data;
      } catch (error) {
        this.$message.error(error.message);
      }
    },

    navigateToFolder(item) {
      if (item.is_file) return;

      const index = this.path.findIndex(p => p.id === item.id);
      if (index >= 0) {
        this.path = this.path.slice(0, index + 1);
      } else {
        this.path.push(item);
      }

      this.loadFolderContent(item.id);
    },

    showCreateDialog() {
      this.formData = {
        ...this.getDefaultFormData(),
        name: '新建文件夹',
        parent_id: this.currentFolderId
      };
      this.isEditMode = false;
      this.showDialog = true;
    },

    showEditDialog(item) {
      this.formData = { ...item };
      this.isEditMode = true;
      this.showDialog = true;
    },

    async saveItem() {
      try {
        this.formData.parent_id = this.currentFolderId;

        const api = this.isEditMode ? user_space_update : user_space_create;
        const result = await postJson(api, this.formData);

        if (result.code !== 1) {
          throw new Error(result.msg || '操作失败');
        }

        this.$message.success('操作成功');
        this.showDialog = false;
        await this.loadFolderContent(this.currentFolderId);
      } catch (error) {
        this.$message.error(error.message);
      }
    },

    async deleteItem(item) {
      try {
        await this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const result = await postJson(user_space_delete, { id: item.id });

        if (result.code !== 1) {
          throw new Error(result.msg || '操作失败');
        }

        this.$message.success('删除成功');
        this.loadFolderContent(this.currentFolderId);
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message);
        }
      }
    },

    downloadFile(item) {
      if (item.is_file) {
        const url = `${item.path}${item.path.includes('?') ? '&' : '?'}download=true`;
        const link = document.createElement('a')
        link.href = url
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    },

    handleUploadSuccess(response) {
      this.$message.success('文件上传成功');
      this.formData = {
        ...this.getDefaultFormData(),
        name: response.filename || '上传文件',
        is_file: true,
        path: response.data,
        parent_id: this.currentFolderId
      };
      this.saveItem();
    },

    handleUploadError(error) {
      this.$message.error('文件上传失败');
      console.error('Upload error:', error);
    }
  }
};
</script>

<style scoped>
.file-item {
  width: 10rem;
  cursor: pointer;
}

.file-icon {
  width: 5rem;
}

</style>